<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Controller\AbstractController;
use App\JsonRpc\CalculatorServiceInterface;
use App\JsonRpc\MathValue;
use App\Model\User;
use App\Request\Api\User\LoginRequest;
use App\Request\Api\User\RegisterRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;

class UserController extends AbstractController
{
    /**
     * @Inject
     * @var \Phper666\JWTAuth\JWT
     */
    protected $jwt;

    public function user()
    {
        return $this->success(Context::get('user'));
    }

    public function login(LoginRequest $request)
    {
        $data = $request->validated();

        $user = User::where('nick_name', $data['nick_name'])->first();
        if (! $user) {
            return $this->response->json(['code' => 404, 'message' => '用户未注册'])->withStatus(404);
        }

        if (! check($data['password'], $user['password'])) {
            return $this->response->json(['code' => 400, 'message' => '密码错误'])->withStatus(400);
        }

        $token = $this->jwt->setScene('user')->getToken(['id' => $user->id, 'nick_name' => $user->nick_name]);

        return $this->success([
            'token'  => (string) $token,
            'expire' => $this->jwt->getTTL(),
        ]);
    }

    public function register(RegisterRequest $request)
    {
        $data             = $request->validated();
        $data['password'] = bcrypt($data['password']);

        return $this->success(User::create($data));
    }

    public function sum()
    {
        $client = ApplicationContext::getContainer()->get(CalculatorServiceInterface::class);

        $result = $client->sum(new MathValue(1), new MathValue(2));

        return $this->success(['value' => $result]);
    }
}
